import { defineStore } from "pinia";
import axios from "axios";
import dayjs from "dayjs";
import { h } from "vue";
import { ElMessageBox } from "element-plus";
import useCommonStore from "@/store/common.js";
import pina from "@/store/index.js";
const commonStore = useCommonStore(pina);

const useStore = defineStore({
  id: "activity",
  state: () => ({
    militaryStatus: [],
    militaryStatusLoaded: false,
    generalStatus: [],
    generalStatusLoaded: false,
    impotrantStatus: [],
    impotrantStatusLoaded: false,
    concernedMilitaries: [
      "太平寺",
      "温江",
      "邛崃",
      "彭州",
      "夹江",
      "广汉",
      "遂宁",
      "新津",
      "绵阳",
      "中江",
      "泸州",
      "大足",
      "白市驿",
    ],
    concernedAirports: [
      "ZUUU",
      "ZUTF",
      "ZUMY",
      "双流",
      "天府",
      "绵阳",
      "成都",
      "太平寺",
      "温江",
      "邛崃",
    ],
    runwayCodeZUUU: "",
    runwayCodeZUTF: "",
    runwayCodeZUMY: "",
    runwayLoaded: false,
    runwayVersion: -1,
    runwayUpdate: "",
    currentDiversion: [],
  }),
  getters: {
    runwayDirections() {
      return (
        this.runwayCodeZUUU.substr(0, 1) + this.runwayCodeZUTF.substr(0, 1)
      );
    },
    isActiveWJ() {
      return (
        this.militaryStatus.filter((cell) =>
          (cell.arrField + cell.depField + cell.unit).includes("温江")
        ).length > 0
      );
    },
    opMode() {
      return this.runwayDirections + (this.isActiveWJ ? "WJ" : "");
    },
  },
  actions: {
    requestData() {
      this.loadMilitaryData().then((source) =>
        this.fetchMilitaryChanges(source)
      );
      this.loadGeneralData();
      this.loadImportantData();
      this.loadRunwayCode();
      this.loadCurrentDiversion();
    },
    fetchMilitaryChanges(
      { status, respond, origion, equal, loaded },
      force = false
    ) {
      if (!loaded) {
        // console.log("fetchMilitaryChanges", "ignored due to not loaded");
        return null;
      } else if (equal) {
        // console.log("fetchMilitaryChanges", "ignored due to data equal");
        return null;
      }
      let oldData = {};
      for (let i = 0; i < origion.length; i++) {
        let item = origion[i];
        if (
          this.concernedMilitaries.includes(item.unit) ||
          this.concernedMilitaries.includes(item.arrField) ||
          this.concernedMilitaries.includes(item.depField)
        ) {
          // unit
          if (!oldData[item.unit]) {
            oldData[item.unit] = new Array();
          }
          if (!oldData[item.unit].includes(item.name)) {
            oldData[item.unit].push(item.name);
          }
          // arrField
          if (!oldData[item.arrField]) {
            oldData[item.arrField] = new Array();
          }
          if (!oldData[item.arrField].includes(item.name)) {
            oldData[item.arrField].push(item.name);
          }
          // depField
          if (!oldData[item.depField]) {
            oldData[item.depField] = new Array();
          }
          if (!oldData[item.depField].includes(item.name)) {
            oldData[item.depField].push(item.name);
          }
        }
      }
      let newData = {};
      for (let i = 0; i < respond.length; i++) {
        let item = respond[i];
        if (
          this.concernedMilitaries.includes(item.unit) ||
          this.concernedMilitaries.includes(item.arrField) ||
          this.concernedMilitaries.includes(item.depField)
        ) {
          // unit
          if (!newData[item.unit]) {
            newData[item.unit] = new Array();
          }
          if (!newData[item.unit].includes(item.name)) {
            newData[item.unit].push(item.name);
          }
          // arrField
          if (!newData[item.arrField]) {
            newData[item.arrField] = new Array();
          }
          if (!newData[item.arrField].includes(item.name)) {
            newData[item.arrField].push(item.name);
          }
          // depField
          if (!newData[item.depField]) {
            newData[item.depField] = new Array();
          }
          if (!newData[item.depField].includes(item.name)) {
            newData[item.depField].push(item.name);
          }
        }
      }
      let messages = new Array();
      for (let key in newData) {
        newData[key].sort();
        if (oldData[key]) {
          oldData[key].sort();
          if (newData[key].join() != oldData[key].join()) {
            messages.push(
              h(
                "div",
                { style: { padding: "6px 0", textAlign: "justify" } },
                `${key}批次变更了，最新批次：${newData[key].join("、")}`
              )
            );
          }
        } else {
          messages.push(
            h(
              "div",
              { style: { padding: "6px 0", textAlign: "justify" } },
              `${key}开飞了，批次：${newData[key].join("、")}`
            )
          );
        }
      }
      for (let key in oldData) {
        if (!newData[key]) {
          messages.push(
            h(
              "div",
              { style: { padding: "6px 0", textAlign: "justify" } },
              `${key}活动结束了`
            )
          );
        }
      }
      if (force) {
        messages.push(h("div", null, "测试信息，测试信息，测试信息"));
      }
      if (messages.length > 0) {
        messages.push(
          h(
            "div",
            {
              style: {
                paddingTop: "4px",
                fontSize: "12px",
                opacity: "0.5",
              },
            },
            "@" + dayjs().format("HH:mm:ss")
          )
        );
        ElMessageBox({
          title: "活动信息变更",
          message: h("div", null, messages),
          draggable: true,
          customClass: "msgbox-rock-gradient",
          confirmButtonClass: "msgbox-main-btn",
          confirmButtonText: "知道了",
        });
      } else {
        // console.log("fetchMilitaryChanges", "After analysis, ignored!");
      }
      // console.log("fetchMilitaryChanges", oldData, newData);
    },
    // fetchGeneralChanges({ status, respond, origion, equal }) {},
    // fetchImportantChanges({ status, respond, origion, equal }) {},
    loadMilitaryData() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/activity_military_load.php")
          .then((response) => {
            if (response.data.status == 0) {
              // console.log('[info]', response.data);
            }
            if (response.data.data) {
              let respond = JSON.stringify(response.data.data);
              let origion = JSON.stringify(this.militaryStatus);
              resolve({
                status: response.data.status,
                respond: JSON.parse(respond),
                origion: JSON.parse(origion),
                equal: respond == origion,
                loaded: this.militaryStatusLoaded,
              });
              this.militaryStatus = response.data.data;
              this.militaryStatusLoaded = true;
            } else {
              console.warn("military activity loading warning", response.data);
              // reject({ msg: "loadMilitaryDataFailed" });
            }
          })
          .catch((error) => {
            console.error("military activity loading error", error);
            reject(error);
          });
      });
    },
    loadGeneralData() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/activity_general_load.php")
          .then((response) => {
            if (response.data.status == 0) {
              // console.log('[info]', response.data);
            }
            if (response.data.data != null) {
              let respond = JSON.parse(JSON.stringify(response.data.data));
              let origion = JSON.parse(JSON.stringify(this.generalStatus));
              resolve({
                status: response.data.status,
                respond,
                origion,
                equal: respond == origion,
                loaded: this.generalStatusLoaded,
              });
              this.generalStatus = response.data.data;
              this.generalStatusLoaded = true;
            } else {
              this.generalStatus = [];
              // console.log('[exception]', response.data);
            }
          })
          .catch((error) =>
            console.error("general activity loading error", error)
          );
      });
    },
    loadImportantData() {
      return new Promise((resolve, reject) => {
        axios
          .get("api/activity_important_load.php")
          .then((response) => {
            if (response.data.status == 0) {
              // console.log('[info]', response.data);
            }
            if (response.data.data) {
              let respond = JSON.parse(JSON.stringify(response.data.data));
              let origion = JSON.parse(JSON.stringify(this.impotrantStatus));
              resolve({
                status: response.data.status,
                respond,
                origion,
                equal: respond == origion,
                loaded: this.impotrantStatusLoaded,
              });
              this.impotrantStatus = response.data.data;
              this.impotrantStatusLoaded = true;
            } else {
              console.warn("important activity loading warning", response.data);
            }
          })
          .catch((error) =>
            console.error("important activity loading error", error)
          );
      });
    },
    loadRunwayCode() {
      return new Promise((resolve, reject) => {
        axios
          .post("api/common_params.php", {
            method: "GET",
            keys: [
              "ATCOS_RWY_MODE_CODE_ZUUU",
              "ATCOS_RWY_MODE_CODE_ZUTF",
              "ATCOS_RWY_MODE_CODE_ZUMY",
              "ATCOS_RWY_MODE_TIMESTAMP_RECIVE",
              "ATCOS_RWY_MODE_TIME_RECIVE",
            ],
          })
          .then((response) => {
            resolve(response.data);
            this.runwayCodeZUUU = response.data.ATCOS_RWY_MODE_CODE_ZUUU;
            this.runwayCodeZUTF = response.data.ATCOS_RWY_MODE_CODE_ZUTF;
            this.runwayCodeZUMY = response.data.ATCOS_RWY_MODE_CODE_ZUMY;
            this.runwayVersion = response.data.ATCOS_RWY_MODE_TIMESTAMP_RECIVE;
            this.runwayUpdate = response.data.ATCOS_RWY_MODE_TIME_RECIVE;
            this.runwayLoaded = true;
            // console.log(
            //   "loadRunwayCode",
            //   "ZUUU:",
            //   this.runwayCodeZUUU,
            //   "ZUTF:",
            //   this.runwayCodeZUTF,
            //   "ZUTF:",
            //   this.runwayCodeZUMY,
            //   "Update:",
            //   this.runwayUpdate
            // );
          })
          .catch((error) => console.error("loadRunwayCode", error));
      });
    },
    loadCurrentDiversion() {
      // let url = `api/flight_diversion_get.php?fake=${
      //   commonStore.isReal ? 0 : 1
      // }`;
      // let url = "api/flight_diversion_get.php?fake=1";
      let url = "api/flight_diversion_get.php";
      return new Promise((resolve, reject) => {
        // ?fake=${commonStore.isReal ? 0 : 1}
        axios
          .get(url)
          .then((response) => {
            this.currentDiversion = response.data.content;
            resolve(response.data);
          })
          .catch((error) => {
            console.error("loadCurrentDiversion", error);
            reject(error);
          });
      });
    },
  },
});

export default useStore;
